<?php

namespace app\api\middleware;

use app\api\common\Auth;
use app\api\common\common;
use think\facade\Cache;

class TokenAuth
{
    /**
     * @param $request
     * @param \Closure $next
     * @return \think\Response
     */
    public function handle($request, \Closure $next)
    {
        // 添加中间件执行代码
        $header = request()->header();
        if(empty($header['token'])){
            $common = new common();
            return $common->result(null,'请先登陆！','10001');
        }
        $data = Auth::checkSignkey($header);
        //获取用户id和username
        $cacheKey = $data['time'].'apiUserInfo'.$data['ip'];
        $userInfo = Cache::get($cacheKey);
        //检查用户是否被禁用
        //Todo 由于status是在登陆的时候就存入了缓存，因此用户保持登录时禁用不生效，可以改进一下，如禁用用户时清除该用户缓存
        if($userInfo['status'] == 0){
            $common = new common();
            return $common->result(null,'很抱歉，账户被封禁，请联系管理员！','100010');
        }
        $request->apiUserInfo = $userInfo;
        return $next($request);

    }
}
